import { expect } from '@jest/globals';
import fse from 'fs-extra';
import path from 'path';

import { runHvigorAsync } from '../../common/common';
import { initPreviewConfigFile } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  }
};

/**
 *  新建一个emptyAbility-API10-STAGE-APP类型的工程， 没有entry\src\mock\mock-config.json5文件，调用预览器报错
 *
 * @param {Project} project
 * @param {TestTaskOption} taskConfig
 * @param {ICaseRecord} record
 * @return res
 */
const testfun: TestCaseFun = async (project, taskConfig, record) => {
  // 1. 还原场景，删除 entry\src\mock\mock-config.json5
  const entryRootPath = project.getModule('entry').moduleRootPath();
  const mockPath = path.resolve(entryRootPath, 'src', 'mock');
  await fse.remove(mockPath);
  await initPreviewConfigFile(entryRootPath);

  // 2. 运行编译脚本
  // eslint-disable-next-line max-len
  const commands: string[] = '--mode module -p module=entry@default -p product=default -p pageType=page -p compileResInc=true -p previewMode=true -p buildRoot=.preview PreviewBuild --watch --parallel --daemon'.split(' ');
  const result = await runHvigorAsync(project.projectRootPath(), commands);
  record.addStep('执行预览构建', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
};

TestCaseBuilder.builder()
  .caseName('DTS2023112702095')
  .description('【DevEco Studio】【SDV】【修改引入】【HOS单框架】【编译构建】新建api10，11工程，预览和仪器测试报错')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.DTS).build())
  .testFun(testfun)
  .load();
